package com.bwie.test;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.domain.Shop;
import com.bwie.es.EsShop;
import com.bwie.mapper.ShopMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: lrz
 * @Date: 2024/10/31 17:51
 * @Description:
 **/
@Component
@Slf4j
public class SysShop implements Job {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    ShopMapper shopMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        log.info("开始同步数据");

        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(EsShop.class);
        if(!indexOperations.exists()){
            indexOperations.create();

            Document mapping = indexOperations.createMapping();
            indexOperations.putMapping(mapping);
        }

        List<Shop> shops = shopMapper.selectList(null);

        for (Shop shop : shops) {
            EsShop esShop = BeanUtil.toBean(shop, EsShop.class);

            elasticsearchRestTemplate.save(esShop);
        }

        log.info("同步数据成功");
    }
}
